import client from "../../utils/pool.mjs"
import { jsonResponse } from "@/utils/index.mjs";
import { generateToken } from '@/service/auth.mjs'

export async function POST(request) {

    // 从body中获取phone和pwd
    const formData = await request.json()
    console.log(formData)
    const phone = formData.phone
    const pwd = formData.pwd
    // 从user库里面查询phone是否存在，存在的话再对比密码；使用ORM方法
    const user = await client.user.findFirst({
        where: {
            phone: phone.toString()
        }
    })
    // 使用prisma查询user表里面的phone和pwd是否匹配
    if (!user) {
        return jsonResponse(400, {
            message: '账号或密码错误'
        })
    }
    if (+user.pwd !== +pwd) {
        return jsonResponse(400, {
            message: '账号或密码错误'
        })
    }
    console.log('user:', user)
    const token = await generateToken({ user_id: user.id })
    console.log('token:', token)
    return jsonResponse(200, { token, time: +new Date() })
}
